package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.service.CommentService;
import cn.com.connext.scrm.service.WxAPIService;
import cn.com.connext.scrm.service.dto.CommentDTO;
import cn.com.connext.scrm.service.dto.CommentVM;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.service.mapper.CommentMapper;
import cn.com.connext.scrm.web.rest.errors.MyErrorCode;
import cn.com.connext.scrm.web.rest.vm.CommentUserIdVM;
import cn.com.connext.scrm.web.rest.vm.NoteIdUserIdVM;
import cn.com.connext.scrm.web.rest.vm.QueryIdVM;
import com.alibaba.fastjson.JSONObject;
import com.codahale.metrics.annotation.Timed;
import com.connext.common.exception.ErrorCode;
import com.connext.common.exception.ServiceException;
import com.connext.common.web.rest.BaseResource;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URISyntaxException;
import java.util.List;

/**
 * Created by YANG205 on 2018/6/27.
 */
@RestController
@RequestMapping("/api/comment")
public class CommentResource extends BaseResource {
    private final Logger log = LoggerFactory.getLogger(CommentResource.class);

    @Autowired
    private CommentService commentService;

    @Autowired
    private WxAPIService wxAPIService;

    public CommentResource() {
        super("Comment");
    }

    @GetMapping("/commentList/{noteId}")
    @Timed
    @ApiOperation(value = "获取评论列表（后台管理）", tags = {"评论列表"}, notes = "获取评论列表（后台管理）")
    public ResponseEntity<Page<CommentDTO>> getCommentList(@ApiParam Pageable pageable,
                                                           @PathVariable String noteId,
                                                           @PathVariable String unionId) {
        if (StringUtils.isEmpty(noteId)) {
            throw new ServiceException(MyErrorCode.ERROR_NOTEID_EMPTY);
        } else {
            CommentDTO commentDTO = new CommentDTO();
            try {
                Page<CommentDTO> commentDTOPage = commentService.getAllComments(pageable, commentDTO);
                return pagedResponse(commentDTOPage);
            } catch (Exception e) {
                log.error("CommentResource->getCommentList:{}", e);
                return null;
            }
        }
    }

    @Deprecated
    @GetMapping("/commentListForWeChat")
    @Timed
    @ApiOperation(value = "获取评论列表（小程序）", tags = {"评论列表"}, notes = "获取评论列表（小程序）")
    public ResponseEntity<List<CommentDTO>> getCommentListForWeChat(@RequestParam String noteId,
                                                                    @RequestParam String userId) {
        if (StringUtils.isEmpty(noteId)) {
            throw new ServiceException(MyErrorCode.ERROR_NOTEID_EMPTY);
        }
        if (StringUtils.isEmpty(userId)) {
            throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
        }
        List<CommentDTO> commentDTOList = commentService.getAllComment(noteId, userId);

        return entityResponse(commentDTOList);
    }

    @PostMapping("/commentListForWeChat")
    @Timed
    @ApiOperation(value = "获取评论列表（小程序）", tags = {"评论列表"}, notes = "获取评论列表（小程序）")
    public ResponseEntity<List<CommentDTO>> getCommentListForWeChat(@RequestBody NoteIdUserIdVM vm) {
        if (StringUtils.isEmpty(vm.getNoteId())) {
            throw new ServiceException(MyErrorCode.ERROR_NOTEID_EMPTY);
        }
        if (StringUtils.isEmpty(vm.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
        }
        List<CommentDTO> commentDTOList = commentService.getAllComment(vm.getNoteId(), vm.getUserId());

        return entityResponse(commentDTOList);
    }

    @PostMapping("/create")
    @Timed
    @ApiOperation(value = "评论帖子", tags = {"评论列表"}, notes = "评论帖子")
    public JsonResult create(@RequestBody CommentVM commentVM) throws URISyntaxException {
        log.debug("REST to create Comment:{}", commentVM);
        if (StringUtils.isNotEmpty(commentVM.getId())) {
            throw new ServiceException(ErrorCode.ERROR_ID_EXISTS);
        }
        if (StringUtils.isEmpty(commentVM.getNoteId())) {
            throw new ServiceException(MyErrorCode.ERROR_NOTEID_EMPTY);
        }
        if (StringUtils.isEmpty(commentVM.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
        }
        if (StringUtils.isEmpty(commentVM.getReplyType().toString())) {
            throw new ServiceException(MyErrorCode.ERROR_REPLYTYPE_EMPTY);
        } else {
            if (1 == commentVM.getReplyType()) {
                if (StringUtils.isEmpty(commentVM.getReplyUserId())) {
                    throw new ServiceException(MyErrorCode.ERROR_REPLYUSERID_EMPTY);
                }
                if (StringUtils.isEmpty(commentVM.getReplyCommentId())) {
                    throw new ServiceException(MyErrorCode.ERROR_REPLYCOMMENTID_EMPTY);
                }
            }
        }

        JsonResult result = commentService.createComment(commentVM);
        return result;


    }

    @Deprecated
    @GetMapping("/likeComment/{commentId}/{userId}")
    @Timed
    @ApiOperation(value = "评论点赞", tags = {"评论列表"}, notes = "评论点赞")
    public JsonResult likeComment(@PathVariable(value = "commentId") String commentId,
                                  @PathVariable(value = "userId") String userId) throws URISyntaxException {
        log.debug("REST to like Comment : {}", commentId, userId);
        if (StringUtils.isEmpty(commentId)) {
            throw new ServiceException(MyErrorCode.ERROR_COMMENTID_EMPTY);
        }
        if (StringUtils.isEmpty(userId)) {
            throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
        }

        JsonResult result =new JsonResult();
        commentService.likeComment(commentId, userId);
        return result;
    }

    @PostMapping("/likeComment")
    @Timed
    @ApiOperation(value = "评论点赞", tags = {"评论列表"}, notes = "评论点赞")
    public JsonResult likeComment(@RequestBody CommentUserIdVM vm) throws URISyntaxException {
        log.debug("REST to like Comment : {}", vm.getCommentId(), vm.getUserId());
        if (StringUtils.isEmpty(vm.getCommentId())) {
            throw new ServiceException(MyErrorCode.ERROR_COMMENTID_EMPTY);
        }
        if (StringUtils.isEmpty(vm.getUserId())) {
            throw new ServiceException(MyErrorCode.ERROR_USERID_EMPTY);
        }

        JsonResult result =new JsonResult();
        commentService.likeComment(vm.getCommentId(), vm.getUserId());
        return result;
    }

    @PostMapping("/deleteComment")
    @Timed
    @ApiOperation(value = "评论点赞", tags = {"评论列表"}, notes = "评论点赞")
    public ResponseEntity deleteComment(@RequestBody QueryIdVM vm){
        JsonResult result = new JsonResult();
        try{
            if (vm == null){
                throw new ServiceException(ErrorCode.ERROR_ID_EXISTS);
            }
            commentService.deleteById(vm.getId());
            result.setState(0);
            result.setMessage("删除成功");
            return entityResponse(result);
        }catch (Exception e){
            log.error("删除失败:{}", e);
            result.setMessage("删除失败");
            result.setState(1);
            return entityResponse(result);
        }
    }
}
